<template>
  <div>
    <h3>发布留言</h3>
    <div class="view">
      <div class="item">
        <div class="field">主题：</div>
        <div class="value">
          <n-input placeholder="请输入主题" v-model:value="form.title" />
        </div>
      </div>
      <div class="item">
        <div class="field">内容：</div>
        <div class="value">
          <n-input type="textarea" placeholder="请输入内容" v-model:value="form.content" />
        </div>
      </div>
      <div class="item">
        <div class="field"></div>
        <div class="value">
          <n-button type="info" @click="create" :loading="requesting" :disabled="requesting">发布留言</n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";

const emits = defineEmits(['reloadList'])
const requests = useRequests()
const message = useMessage()
const notify = useNotification()

const form = ref({
  title: null,
  content: null
})

const requesting = ref(null)
const create = () => {
  if (requesting.value) {
    return false
  }

  if (!form.value.title?.length || !form.value.content?.length) {
    return message.info("标题和内容不能为空")
  }

  requesting.value = true
  requests.message.create(form.value).then(resp => {
    requesting.value = false
    if (resp.ret === 0) {
      emits('reloadList')
      message.success("发布成功")
    } else {
      message.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    requesting.value = false
    console.log(err)

    notify.error({title: "出错了", content: err.toString(), duration: 3000})
  })
}
</script>

<style lang="scss" scoped>
.view {
  .item {
    margin: .5rem 0;
    display: flex;

    .field {
      min-width: 3.25rem;
    }

    .value {
      flex: 1;
    }
  }
}
</style>
